package mts.messages;

import java.util.ArrayList;

import mts.common.CommonSettings;
import mts.constants.MessageType;
import mts.groupdispatcher.FloorRequest;

public class RequestMessage extends Message {
	public static final int INDEX_NEW_HALL_CALLS = Message.INDEX_MESSAGE_TYPE + 1;
	public static final int INDEX_CANCEL_HALL_CALLS = INDEX_NEW_HALL_CALLS + CommonSettings.NUMBER_OF_FLOORS;
	
	public static final int MESSAGE_LENGTH = INDEX_CANCEL_HALL_CALLS + CommonSettings.NUMBER_OF_FLOORS;
	
	private ArrayList<Byte> newHallCalls = new ArrayList<Byte>(CommonSettings.NUMBER_OF_FLOORS);
	private ArrayList<Byte> cancelledHallCalls = new ArrayList<Byte>(CommonSettings.NUMBER_OF_FLOORS);
	
	public ArrayList<Byte> getNewHallCalls() {
		return newHallCalls;
	}
	
	
	public RequestMessage() {
		super(MessageType.STATUS_REQUEST);
	}
	
	public static RequestMessage deserialize(byte[] data) {
		RequestMessage requestMessage = new RequestMessage();
	
		for (byte i = 0; i < CommonSettings.NUMBER_OF_FLOORS; i++) {
			int dataIndex = i + INDEX_NEW_HALL_CALLS;
			if (data[dataIndex] != 0) {
				requestMessage.newHallCalls.add(i);
			}
		}
		
		for (byte i = 0; i < CommonSettings.NUMBER_OF_FLOORS; i++) {
			int dataIndex = i + INDEX_CANCEL_HALL_CALLS;
			if (data[dataIndex] != 0) {
				requestMessage.cancelledHallCalls.add(i);
			}
		}
		return requestMessage;
		
	}
	
	public byte[] serialize() {
		byte[] data = new byte[MESSAGE_LENGTH];
		
		data[Message.INDEX_MESSAGE_TYPE] = getMessageType().getByteValue();
		for (byte floor: newHallCalls) {
			int dataIndex = INDEX_NEW_HALL_CALLS + floor;
			data[dataIndex] = 1;
		}
		for (byte floor: cancelledHallCalls) {
			int dataIndex = INDEX_CANCEL_HALL_CALLS + floor;
			data[dataIndex] = 1;
		}
			
		return data;
	}
	
	@Override
	public boolean equals(Object other) {
		if (!(other instanceof RequestMessage)) {
			return false;
		}
		
		RequestMessage o = (RequestMessage)other;
		
		return newHallCalls.equals(o.newHallCalls) &&
				cancelledHallCalls.equals(o.cancelledHallCalls);
				
	}
	
	@Override
	public String toString() {
		return "RequestMessage [" +
		"messageType: " + getMessageType() +
		", newHallCalls: " + newHallCalls.toString() +
		", cancelHallCalls: " + cancelledHallCalls.toString() +
		"]";				
	}

	public void addNewHallCall(FloorRequest floorRequest) {
		newHallCalls.add(floorRequest.getFloor());
		
	}

	public void addCancelledHallCall(FloorRequest floorRequest) {
		cancelledHallCalls.add(floorRequest.getFloor());
		
	}
	
}
